//购物车的纯函数
import { ADD_CART, EDIT_CART } from '../content';

const initCartList = [];
const cartlist = (state = initCartList, action) => {
    const { type, data } = action;
    switch (type) {
        case ADD_CART:
            //判断是新增还是修改数量
            //找到从容器组件传过来的id
            const { id } = data;
            //如果index = -1 没找到这条记录,不等于-1 ,说明找到了，需要修改数量
            const index = state.findIndex(value => value.id === id);
            if (index === -1) {//新增
                const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
                var result = "";//接收生成好的随机数
                for (var i = 0; i < 24; i++) {
                    result += arr[Math.floor(Math.random() * 16)];
                }
                data.cartId = result;
                /*end*/
                return [...state, data];
            } else {//修改数量
                state[index].num++;
                return [...state];
            }
        case EDIT_CART://修改购物车的状态值
            return [...data];
        default:
            return state;
    }
}

export default cartlist;